# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  
@software: PyCharm 
@file: class_structure2.py 
@time: 2019/6/19 17:04
"""
'''
1.简化数据结构的初始化，省去烦人的__init__()初始化函数
2.增加关键字参数设置
'''

class Structure2:
    _fields = []

    def __init__(self, *args, **kwargs):
        if len(args) > len(self._fields):
            raise TypeError('Expected {} arguments'.format(len(self._fields)))

        # set all of the positional arguments
        for name, value in zip(self._fields, args):
            setattr(self, name, value)

        # Set the remaining keyword arguments
        for name in self._fields[len(args):]:
            setattr(self, name, kwargs.pop(name))

        # Check for any remaining unknown arguments
        if kwargs:
            raise TypeError('Invalid argument(s):{}'.format(','.join(kwargs)))


# Example use
if __name__ == '__main__':
    class Stock(Structure2):
        _fields = ['name', 'share', 'price']

    s1 = Stock('Tom', 50, 91.1)
    print(vars(s1))
    s2  = Stock('Tom',50, price=91.1)
    print(vars(s2))
    s3 = Stock(name='Tom', share=3.4, price=55)
    print(s3.__dict__) #= print(vars(s3))

    print('不能增加_fields列表之外元素，否则回报错！')
    # s4 = Stock('Tom',50, price=91.1, aa=2)
    # print(s4)